package com.fms.security;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fms.constant.Reference;
import com.fms.entity.SysDept;
import com.fms.entity.SysUser;
import com.fms.mapper.SysDeptMapper;
import com.fms.mapper.SysUserMapper;
import com.fms.util.BaseContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class DBUserDetailManager implements UserDetailsService {
    private final SysUserMapper sysUserMapper;

    private final SysDeptMapper sysDeptMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("账号为{}的用户正在校验用户名", username);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);
        log.info("查找到{}的用户", sysUser);
        if(sysUser==null){
            throw new UsernameNotFoundException("不存在"+username);
        }else if(sysUser.getStatus()==0){
            throw new UsernameNotFoundException(username+"账号已被禁用");
        }
        LambdaQueryWrapper<SysDept> deptLambdaQueryWrapper=new LambdaQueryWrapper<>();
        deptLambdaQueryWrapper.eq(SysDept::getId, sysUser.getDeptId());
        SysDept sysDept = sysDeptMapper.selectOne(deptLambdaQueryWrapper);
        if(sysDept==null){
            throw new UsernameNotFoundException(username+"的角色不存在");
        }
        //存入userId到线程变量
        BaseContext.setCurrentId(sysUser.getId());
        log.info("登录存入线程变量{}", sysUser.getId());
        log.info("用户{}的角色为{}", username, Reference.ROLE_MAP.get(sysDept.getName()));
        return User.withUsername(username)
                .password(sysUser.getPassword())
                .authorities(Reference.ROLE_MAP.get(sysDept.getName()))
                .build();
    }
}
